document.getElementById('news-link').addEventListener('click', function () {
    showContent('news-edit');

    fetch('/news/manage', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            var newsManageDiv = document.getElementById('news-manage');
            newsManageDiv.innerHTML = '<h2>新闻管理界面</h2>';
            data.news.forEach(news => {
                newsManageDiv.innerHTML += `
<table>
    <tr>
        <td>标题：</td>
        <td>${news.title}</td>
    </tr>
    <tr>
        <td>内容：</td>
        <td>${news.content}</td>
    </tr>
    <tr>
        <td>图片：</td>
        <td><img src="${news.img}" alt="${news.title}" style="width:100px;height:auto;"></td>
    </tr>
    <tr>
        <td>类型：</td>
        <td>${news.type}</td>
    </tr>
    <tr>
        <td>创建时间：</td>
        <td>${news.create_time}</td>
    </tr>
    
</table>
<button onclick="delete_news('${news.id}')" class="btn btn-lg btn-primary btn-block">删除新闻</button>
<button onclick="update_news('${news.id}')" class="btn btn-lg btn-primary btn-block">更新新闻</button>
<br>
`;
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
});

document.getElementById('add-news').addEventListener('click', function () {
    document.getElementById('news-form').style.display = 'block'; // 显示新增新闻的表单
});

document.getElementById('submit-news').addEventListener('click', function () {
    var newsData = {
        title: document.getElementById('news-title').value,
        content: document.getElementById('news-content').value,
        img: document.getElementById('news-img').value,
        type: document.getElementById('news-type').value
    };

    fetch('/news/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(newsData)
    })
        .then(response => response.json())
        .then(data => {
            alert('新闻新增成功！');
            document.getElementById('news-form').style.display = 'none'; // 隐藏表单
            location.reload();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('新增失败，请重试！');
        });
});

function delete_news(newsId) {
    fetch('/news/delete/' + newsId + '/', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                throw new Error('删除新闻失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}
